import hashlib
import json
import random

from https import HttpRequest as http
from utils.time_util import stamp_ms


class getui_utils:
    '''
    个推工具类
    '''

    appId = "BgiluV7RCw7ClibpiieVG1"
    appKey = "TxjmRGAyXXANgxWHoZpub7"
    masterSecret = "7FqfOnehWf6O5eWsKt77v4"

    baseUrl = "https://restapi.getui.com/v2/" + appId
    authUrl = baseUrl + "/auth"
    pushUrl = baseUrl + "/push/single/cid"

    requestId = str(random.randint(1000000000, 999999999999999999999999999999))
    # authTime = 0
    authVaule = ""

    def _getAuth(self):
        """
        获取鉴权
        """
        # global authTime
        auth = ""
        # if self.authTime == 0 or stamp_ms() > self.authTime:
        timestamp = stamp_ms()
        sign = hashlib.sha256((self.appKey + str(timestamp) + self.masterSecret).encode('utf-8')).hexdigest()
        headers = {"content-type": "application/json;charset=utf-8"}
        params = {"sign": sign, "timestamp": str(timestamp), "appkey": self.appKey}
        result = http.post_web(url=self.authUrl, params=json.dumps(params), h=headers)
        if result is not None and "data" in result.keys():
            if "expire_time" in result["data"].keys() and "token" in result["data"].keys():
                self.authTime = int(result["data"]["expire_time"])
                auth = result["data"]["token"]
        return auth

    def pushMsg(self, title, body, voice=""):
        """
        消息推送
        """

        params = {
            "request_id": self.requestId,
            "settings": {"ttl": 3600000},
            "audience": {"cid": ["20e057f83e7ee01c002d334c628b15a0"]},
            "push_message": {"transmission": "交易预警"},
            "push_channel": {
                "ios": {
                    "type": "notify",
                    "payload": "自定义消息",
                    "aps": {
                        "alert": {
                            "title": title,
                            "body": body
                        },
                        "sound": voice,
                        "content-available": 0
                    },
                    "auto_badge": "1"
                }
            }
        }

        auth = self._getAuth()
        headers = {"content-type": "application/json;charset=utf-8", "token": auth}
        returnValue = http.post_web(url=self.pushUrl, params=json.dumps(params), h=headers)
        if returnValue is not None and returnValue != "":
            print("发送成功")
            return True
        else:
            print("发送失败")
            return False